﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SuperSocialShare
{
	internal static class Utility
	{
		internal static string BuildQueryString(params RequestParameter[] parameters)
		{
			List<string> pairs = new List<string>();
			foreach (var item in parameters)
			{
				if(item.IsBinaryData)
					continue;

				var value = string.Format("{0}", item.Value);

				if (!string.IsNullOrEmpty(value))
				{
					pairs.Add(string.Format("{0}={1}", Uri.EscapeDataString(item.Name), Uri.EscapeDataString(value)));
				}
			}
			return string.Join("&", pairs.ToArray());
		}

		internal static string BuildQueryString(IEnumerable<KeyValuePair<string, object>> parameters)
		{
			var reqeustParameters = new List<RequestParameter>();
			foreach (var item in parameters)
			{
				reqeustParameters.Add(new RequestParameter(item.Key, item.Value));
			}

			return BuildQueryString(reqeustParameters.ToArray());
		}

        internal static string BuildQueryString(string baseurl, IEnumerable<KeyValuePair<string, object>> parameters)
        {
            StringBuilder query = new StringBuilder(baseurl);
            query.Append("?");
            query.Append(BuildQueryString(parameters));
            return query.ToString();
        }

        /// <summary>
        /// 用提供的正则表达式提取内容
        /// </summary>
        /// <param name="pattern">正则式</param>
        /// <param name="content">被匹配的文本</param>
        /// <returns></returns>
        internal static string GetRegexContent(string pattern,string content) 
        {
            Regex regex = new Regex(pattern,RegexOptions.IgnoreCase);
            Match match = regex.Match(content);
            if (match.Success)
                return match.Value;
            return null;
        }
	}
}
